package com.clear.wechat.handler;

import com.clear.wechat.handler.enums.WechatMSGEnum;
import com.clear.wechat.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WechatMsgHandler {

    private static final String KEY_WORD = "验证码";

    private static final String LOGIN_PREFIX = "loginCode";

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取枚举类型
     *
     * @return
     */
    @Override
    public WechatMSGEnum getMsgType() {
        return WechatMSGEnum.TEXT_MSG;
    }

    /**
     * 具体业务逻辑，根据枚举类型不同执行不同逻辑
     *
     * @return
     */
    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到文本消息");
        String content = messageMap.get("Content");
        if (!KEY_WORD.equals(content)) {
            return "";
        }
        // ==================只有用户输入文本为：验证码  才执行后续逻辑=========================
        String fromUserName = messageMap.get("FromUserName");   // OpenId
        String toUserName = messageMap.get("ToUserName");
        // 生成验证码
        String code = GenerateVerificationCode(4);

        // ====将验证码写入缓存====
        String codeKey = redisUtil.buildKey(LOGIN_PREFIX, code);
        // loginCode.验证码 openId
        redisUtil.setNx(codeKey, fromUserName, 5L, TimeUnit.MINUTES);

        // =====回调给用户=====
        String codeContent = "您的验证码是：" + code + " ！ 五分钟内有效";
        String replyContent = "<xml>\n" +
                "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + codeContent + "]]></Content>\n" +
                "</xml>";

        return replyContent;
    }

    /**
     * 生成验证码
     *
     * @param num
     * @return
     */
    private String GenerateVerificationCode(int num) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder code = new StringBuilder(4);

        for (int i = 0; i < 4; i++) {
            code.append(characters.charAt(random.nextInt(characters.length())));
        }
        return code.toString();
    }
}
